package com.example.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.example.service.MinIoService;
import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.List;

/**
 * @author SongXuSheng
 * @description: MinIo服务实现类
 * @date 2022/8/18 21:15
 */
@Slf4j
@Service
public class MinIoServiceImpl implements MinIoService {

    private static final String FILE_NAME_PATTERN = "{}_{}";
    @Autowired
    private MinioClient minioClient;


    @Override
    public boolean bucketExists(String bucketName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        return minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
    }

    @Override
    public void createBucket(String bucketName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if (!isExist) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }
    }

    @Override
    public List<Bucket> getAllBuckets() throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        return minioClient.listBuckets();
    }

    @Override
    public String upload(MultipartFile file, String bucketName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        //判断桶是否存在
        boolean b = this.bucketExists(bucketName);
        if (!b){
            this.createBucket(bucketName);
        }
        // 上传文件的原始文件名
        String originalFilename = file.getOriginalFilename();
        // 文件大小
        long fileSize = file.getSize();
        log.info("上传文件的原始文件名：{}，文件大小：{}，文件类型为：{}", originalFilename, fileSize, file.getContentType());
        // 文件名：日期_原始文件名
        String fileName = StrUtil.format(FILE_NAME_PATTERN, DateUtil.format(new Date(), "yyyyMMddHHmmss"), originalFilename);
        log.info("格式化后的文件名：{}", fileName);
        try {
            minioClient.putObject(PutObjectArgs.builder().bucket(bucketName)
                    .object(fileName).stream(file.getInputStream(), fileSize, -1).contentType(file.getContentType()).build());
        } catch (Exception e) {
            log.info("上传文件失败！"+ e.getMessage());
        }
        return fileName;
    }

    @Override
    public String getFileUrl(String bucketName, String fileName) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        BucketExistsArgs bucketArgs = BucketExistsArgs.builder().bucket(bucketName).build();
        boolean bucketExists = minioClient.bucketExists(bucketArgs);
        String url="";
        if (bucketExists){
            GetPresignedObjectUrlArgs getPresignedObjectUrlArgs = GetPresignedObjectUrlArgs.builder()
                    .method(Method.GET)
                    .bucket(bucketName)
                    .object(fileName)
                    .build();
            url=minioClient.getPresignedObjectUrl(getPresignedObjectUrlArgs);
        }
        return url;
    }

    @Override
    public String getFileUrl(String bucketName, String fileName, Integer expires) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        BucketExistsArgs bucketArgs = BucketExistsArgs.builder().bucket(bucketName).build();
        boolean bucketExists = minioClient.bucketExists(bucketArgs);
        String url="";
        if (bucketExists){
            GetPresignedObjectUrlArgs getPresignedObjectUrlArgs = GetPresignedObjectUrlArgs.builder()
                    .method(Method.GET)
                    .bucket(bucketName)
                    .object(fileName)
                    .expiry(expires)
                    .build();
            url=minioClient.getPresignedObjectUrl(getPresignedObjectUrlArgs);
        }
        return url;
    }
}
